package com.fet.refreshOffer.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fet.refreshOffer.HttpHandler;


public class HttpHandlerHttpClientImpl implements HttpHandler {
	
	Log log = LogFactory.getLog(HttpHandlerHttpClientImpl.class);

	public String execMethod(String url, Properties params,
				int soTimeout,int connectTimeout) throws Exception {

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		//V1.1 start;
		if(connectTimeout > 0)
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout);
		if(soTimeout > 0)
			client.getParams().setSoTimeout(soTimeout);
		//V1.1 end;
		String responseString = null;
		
		NameValuePair[] paramArray = getParamsArray( params);
		if(paramArray != null)
			post.setRequestBody(paramArray);
		
		post.setRequestHeader("Content-type", 
			"application/x-www-form-urlencoded; charset=utf-8");
		
		try {
            int statusCode = client.executeMethod(post);
		     if (statusCode != HttpStatus.SC_OK) 
		    	 throw new Exception("Post method failed: " + post.getStatusLine());
		     responseString = getResponseBodyAsString(post);
		}catch(ConnectException e){
			log.error(e);
			throw e;
		} catch (HttpException e) {
		     log.error(e);
		     throw new HttpException("HttpException:" + e.getMessage());
		}catch(Exception e){
			log.error(e);
			throw new Exception("Exception:" + e.getMessage());
		}
		finally {
		     post.releaseConnection();
		}
		
		log.info("responseString : " + responseString);
		
		return responseString;
	}
	
	private String getResponseBodyAsString(PostMethod post) throws Exception{
		if(post == null)
			return null;
		InputStream resStream = post.getResponseBodyAsStream();  
        BufferedReader br = new BufferedReader(new InputStreamReader(resStream));  
        StringBuffer resBuffer = new StringBuffer();  
        String resTemp = "";  
        while((resTemp = br.readLine()) != null){  
            resBuffer.append(resTemp);  
        }  
        String response = resBuffer.toString(); 
		return response;
	}
	
	private NameValuePair[] getParamsArray( Properties params){
		NameValuePair[] paramArray = null;
		if(params != null){
			Enumeration<?> keys = params.propertyNames();
			paramArray = new NameValuePair[params.size()];
			int i = 0;
			while(keys.hasMoreElements()){
				String key = (String)keys.nextElement();
				paramArray[i] = new NameValuePair(key,params.getProperty(key));
				i ++;
			}
		}
		return paramArray;
	}
	
}
